<?php

namespace app\admin\controller\qingdongams\statistic;

use app\admin\controller\qingdongams\Base;
use addons\qingdongams\model\Workorder as WorkorderModel;
use addons\qingdongams\model\Staff;
use think\Exception;

/**
 * 工单分析
 *
 * @icon fa fa-circle-o
 */
class Workorder extends Base
{

    /**
     * PartyBuilding模型对象
     * @var \addons\qingdongams\model\Workorder
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new WorkorderModel();
        $this->assign('typeList',[0=>'请选择', 1=>'部门',2=>'员工']);
        try{
            \think\Db::execute("SET @@sql_mode='';");
        }catch (Exception $e){

        }
    }
    //工单数量分析
    public function index() {
        list($where,$times,$row) = $this->getWhere();//获取where

        $addOrder = WorkorderModel::where($where)//新增工单
        ->field('count(*) as count,FROM_UNIXTIME(createtime,"%Y-%m-%d") as time')
            ->group('time')->select();
        $endWhere = $where;
        unset($endWhere['createtime']);
        $endWhere['end_time'] = ['between', $times];
        $endOrder = WorkorderModel::where($endWhere)->where(['status' => 3])//完成工单
        ->field('count(*) as count,FROM_UNIXTIME(end_time,"%Y-%m-%d") as time')->select();


        $addOrder = $this->getArr($addOrder,'time');
        $endOrder = $this->getArr($endOrder,'time');

        $dateList = getDateList($times[0], $times[1]);
        $result = [];
        foreach ($dateList as $date) {
            $result['date'][]=$date;
            $result['add'][]=intval($addOrder[$date] ?? 0);
            $result['end'][]=intval($endOrder[$date] ?? 0);
        }
        // 表格 create_staff_id
        // 新增数
        $addPeople = WorkorderModel::where($where)->field('count(*) as count,create_staff_id')->group('create_staff_id')->select();
        // 完成数
        $endPeople = WorkorderModel::where($endWhere)->field('count(*) as count,create_staff_id')->group('create_staff_id')->select();

        $staffIds = array_unique(array_merge(array_column($addPeople,'create_staff_id'),array_column($endPeople,'create_staff_id')));
        $staffList = Staff::where('id','in',$staffIds)->column('name','id');

        $addPeople = $this->getArr($addPeople,'create_staff_id');
        $endPeople = $this->getArr($endPeople,'create_staff_id');
        $totalAdd = array_sum($addPeople);
        $totalEnd = array_sum($endPeople);

        $table[] = [
            'name'  =>  '总计',
            'add'    =>  $totalAdd,
            'end'  =>  $totalEnd,
        ];
        foreach ($staffList as $key=>$item) {
            $table[] = [
                'name'  =>  $staffList[$key],
                'add'  =>  isset($addPeople[$key]) ? $addPeople[$key] : 0,
                'end'  =>  isset($endPeople[$key]) ? $endPeople[$key] : 0,
            ];
        }
        $this->view->assign([
            'result'       => $result,
            'table'       => $table,
            'row'         =>    $row
        ]);
        $this->assignconfig('result',$result);
        $this->assignconfig('ids',$row['ids']);
        return $this->view->fetch();
    }


    public function getWhere(){
        $beforeDays = strtotime(date('Y-m-d',strtotime('-30 day', time())));
        $times = [$beforeDays,time()];

        $row['type_id'] = 0;
        $row['ids'] = 0;
        if ($this->request->get()) {
            $params = $this->request->get('row/a');
            if(isset($params['times']) && !empty($params['times'])){
                $timesArr = explode('-', $params['times']);
                $times[0] = $timesArr[0].'-'.$timesArr[1].'-'.$timesArr[2];
                $times[1] = $timesArr[3].'-'.$timesArr[4].'-'.$timesArr[5];
                $times = [strtotime($times[0]),strtotime($times[1])+86400-1];
            }
            $row['type_id'] = $params['type_id'];
            $row['ids'] = $params['ids']?? 0;
            if($params['type_id'] == 1 && $params['ids']){
                $l_ids = Staff::getOneGroupStaffIds($params['ids']);
                $where['create_staff_id'] = ['in', $l_ids];
            }elseif($params['type_id'] == 2 && $params['ids']){
                $where['create_staff_id'] = $params['ids'];
            }
        }
        $row['times'] = implode(' - ',[date("Y-m-d",$times[0]),date("Y-m-d",$times[1])]);
        $where['createtime'] = ['between',$times];
        return [$where,$times,$row];
    }


    public function getArr($data,$key){
        $tradeCount = [];
        foreach ($data as $v) {
            $tradeCount[$v[$key]] = $v['count'];
        }
        return $tradeCount;
    }


}
